﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DNNspot.LiveChat.Common;
using DNNspot.LiveChat.DataModel;
using DotNetNuke.Common;
using DotNetNuke.Entities.Users;

namespace DNNspot.LiveChat.Admin
{
    public partial class EditSession : ModuleBase
    {
        private int? _sessionId;

        // ### EVENTS ######################################################

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadSettings();
                LoadControls();
            }

            LoadSessionId();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Redirect();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Delete();
            Redirect();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Save();
            Redirect();
        }

        protected void rptMessages_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
                BindMessageItem(e);
        }

        // ### PRIVATE FUNCTIONS ###########################################

        private void BindMessageItem(RepeaterItemEventArgs e)
        {
            var message = (Message) e.Item.DataItem;
            var litMessageDivOpen = (Literal)e.Item.FindControl("litMessageDivOpen");
            var lblName = (Label) e.Item.FindControl("lblName");
            var lblBody = (Label) e.Item.FindControl("lblBody");


            litMessageDivOpen.Text = "<div class='message'>";

            if(message.AgentId != null)
            {
                lblName.Text = String.Format("{0} {1}", 
                    message.UpToAgentByAgentId.UpToUserByUserId.FirstName, 
                    message.UpToAgentByAgentId.UpToUserByUserId.LastName);

            }
            else if(message.ClientId != null)
            {
                litMessageDivOpen.Text = "<div class='message self'>";
                lblName.Text = String.Format("{0} {1}",
                    message.UpToClientByClientId.FirstName,
                    message.UpToClientByClientId.LastName);   
            }
            else
            {
                litMessageDivOpen.Text = "<div class='message system'>";
            }

            lblBody.Text = message.Body;
        }

        private void Delete()
        {
            var q = new MessageQuery();
            q.Where(q.SessionId == _sessionId);

            var messages = new MessageCollection();
            messages.Load(q);
            messages.MarkAllAsDeleted();
            messages.Save();

            var session = DataModel.Session.Load(_sessionId);
            session.MarkAsDeleted();
            session.Save();
        }

        private void LoadSessionId()
        {
            _sessionId = null;

            if (Convert.ToInt32(hidSessionId.Value) > -1)
                _sessionId = Convert.ToInt32(hidSessionId.Value);
        }

        private void LoadControls()
        {
            LoadSessionId();

            var session = DataModel.Session.Load(_sessionId);

            if(session.UpToAgentByAgentId != null)
            {
                var user = UserController.GetUserById(Convert.ToInt32(session.UpToAgentByAgentId.PortalId), Convert.ToInt32(session.UpToAgentByAgentId.UserId));
                lblAgent.Text = String.Format("{0} {1} ({2})", user.FirstName, user.LastName, user.Username);
            }
            
            lblName.Text = String.Format("{0} {1}", session.UpToClientByClientId.FirstName, session.UpToClientByClientId.LastName);
            lblEmail.Text = session.UpToClientByClientId.Email;
            lblIp.Text = session.UpToClientByClientId.Ip;
            lblUrlReferrer.Text = session.UrlReferrer;
            lblCategory.Text = session.UpToCategoryByCategoryId.Name;
            lblQuestion.Text = session.Question;
            txtNotes.Text = session.Notes;

            var q = new MessageQuery();
            q.Where(q.SessionId == _sessionId);
            q.OrderBy(q.CreatedDate.Ascending);

            var messages = new MessageCollection();
            messages.Load(q);

            rptMessages.DataSource = messages;
            rptMessages.DataBind();

            if (session.IsActive == false)
                btnDelete.Visible = true;
        }

        private void LoadSettings()
        {
            _sessionId = Convert.ToInt32(Request.QueryString[Params.SessionId]);
            hidSessionId.Value = _sessionId.ToString();
        }

        private void Redirect()
        {
            Response.Redirect(Globals.NavigateURL(TabId));
        }

        private void Save()
        {
            var session = DataModel.Session.Load(_sessionId);
            session.Notes = txtNotes.Text;

            session.Save();
        }
    }
}